from sqlalchemy.orm import Session

from mldong.util import JwtUtil, StrUtil
from modules.sys.models.user import UserOrmModel
from modules.sys.params.auth_param import LoginParam
from modules.sys.vos.auth_vo import LoginToken
class AuthService:
    jwt_secret:str = "aBcDeFgHiJkLmNoPqRsTuVwXyZ12345678"
    def __init__(self, db: Session):
        self.db = db

    def login(self, param: LoginParam)-> LoginToken:
        """
        登录
        :param param: 登录参数
        :return: 登录结果
        """
        userModel: UserOrmModel = self.db.query(UserOrmModel).filter(UserOrmModel.userName == param.userName).first()
        if not userModel:
            return LoginToken(token="",userId="")
        if userModel.isLocked==1: return LoginToken(token="", userId="")
        encryptPassword = StrUtil.md5_encrypt(str(param.password)+userModel.salt)
        if userModel.password != encryptPassword:
            return LoginToken(token="", userId="")
        # 登录成功，生成token
        # 当前permCodes是静态的，实际开发中应该从数据库中查询
        # RBAC权限管理
        """"
        select * from sys_user where id = 1686404946814533633;
            -- 根据用户id查询其拥有的角色id
            select role_id from sys_user_role where user_id = 1686404946814533633;
            -- 根据角色id获取其菜单id
            select menu_id from sys_role_menu where role_id in(select role_id from sys_user_role where user_id = 1686404946814533633)

            -- 根据菜单id获取权限码

            select code from sys_menu where id in (
            select menu_id from sys_role_menu where role_id in(select role_id from sys_user_role where user_id = 1686404946814533633)
            )
        """
        payload = {"userId": userModel.id, "userName": userModel.userName, "permCodes": ["admin","sys:user:page","sys:user:detail"]}
        token = JwtUtil.generate_token(payload, AuthService.jwt_secret)
        return LoginToken(token=token, userId=str(userModel.id))
    
    def logout(self, token: str):
        """
        登出
        :param token: 登录令牌
        :return: 登出结果
        """
        # 删除token
        return True